<template>
  <div class="laboratory_wrap">
    <el-card class="laboratory_wrap_card" v-loading="isLoading">
      <div class="custom-tree-container">
        <div class="title_box">
          <span class="title_text">
            <i class="iconfont icon-shuxingjiegou"></i>
            实验室结构
          </span>
          <div class="add">
            <!-- <el-button type="primary" @click="addLaboratoryClick"> 添加实验室</el-button> -->
          </div>
        </div>
        <el-tree
          :data="dataSource"
          class="lab_tree"
          node-key="id"
          default-expand-all
          ref="treeRef"
          :expand-on-click-node="false"
          :render-content="renderContent"
          :check-on-click-node="true"
          @node-click="treeNodeClick"
          @node-contextmenu="
            (e, a) => {
              rightClick(e, a);
            }
          "
          :highlight-current="true"
        >
          <template #default="{ data }">
            <div class="custom-tree-node">
              <span class="pl-1">{{ data.address }}121</span>
            </div>
          </template>
        </el-tree>

        <!-- <p>Using scoped slot</p> -->
        <!-- <el-tree
          style="max-width: 600px"
          :data="dataSource"
          show-checkbox
          node-key="id"
          default-expand-all
          :expand-on-click-node="false"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span>{{ node.label }}</span>
              <span>
                <a @click="append(data)"> Append </a>
                <a style="margin-left: 8px" @click="remove(node, data)"> Delete </a>
              </span>
            </span>
          </template>
        </el-tree> -->
      </div>
    </el-card>

    <!-- 添加/编辑 实验室Dialog -->
    <el-dialog v-model="isShowAddLaboratoryDialog" :title="`${isAddLabForm ? '添加' : '编辑'}实验室`" width="560">
      <div class="add_laboratory_box">
        <el-form :model="addLaboratoryFormData" :rules="addLaboratoryFormRules" ref="addLaboratoryFormRef">
          <!-- <el-form-item label="实验室名称" label-width="100px" prop="name">
            <el-input v-model="addLaboratoryFormData.name" autocomplete="off" />
          </el-form-item> -->
          <el-form-item label="实验室地址" label-width="100px" prop="address" style="margin-top: 30px">
            <el-input v-model="addLaboratoryFormData.address" autocomplete="off" />
          </el-form-item>
          <!-- <el-form-item label="排序" label-width="100px" style="margin-top: 30px">
            <el-input v-model="addLaboratoryFormData.displayorder" autocomplete="off" />
          </el-form-item> -->
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isShowAddLaboratoryDialog = false">取消</el-button>
          <el-button type="primary" @click="addLaboratoryConfirmClick(addLaboratoryFormRef)"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>

    <vue3-menus :open="isContentMenuOpen" :event="eventVal" :menus="menus.menus">
      <!-- <template #icon="{ menu, activeIndex, index }">{{ activeIndex }}</template> -->
      <template #label="menu">
        <el-icon
          v-if="menu.menu.icons == 'plus'"
          style="position: relative; top: 3px; margin-right: 6px"
          color="#2556d6"
          size="16"
        >
          <Plus />
        </el-icon>
        <el-icon
          v-if="menu.menu.icons == 'edit'"
          style="position: relative; top: 3px; margin-right: 6px"
          color="#2556d6"
          size="16"
        >
          <Edit />
        </el-icon>
        <el-icon v-if="menu.menu.icons == 'delete'" style="position: relative; top: 3px; margin-right: 6px" color="red" size="16">
          <Delete />
        </el-icon>
        <span>{{ menu.menu.label }}</span>
      </template>
    </vue3-menus>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref, nextTick } from "vue";
import { directive } from "vue3-menus";
import { Plus, Delete, Edit } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import LabImg from "./components/labImg.vue";
import LabImg1 from "./components/labImg1.vue";
// ElMessageBox
export default defineComponent({
  name: "Laboratory",
  directives: {
    menus: directive
  }
});
</script>
<script lang="ts" setup>
import type Node from "element-plus/es/components/tree/src/model/node";
import { selectLaboratoryApi, addLaboratoryApi, delLaboratoryApi, editLaboratoryApi } from "@/api/modules/laboratory/index";
import { laboratoryListType } from "@/api/modules/laboratory/type";
import { addLaboratoryFormType } from "./type";

// 当前右键的tree数据
const currentContextmenuData = ref({});

function rightClick(event, target) {
  console.log("当前节点数据", target);
  currentContextmenuData.value = target;
  currentClickNodeId.value = target.id;
  console.log("存储节点数据", currentContextmenuData.value);

  isContentMenuOpen.value = false;
  nextTick(() => {
    eventVal.value = event;
    isContentMenuOpen.value = true;
  });
  event.preventDefault();
}

// 添加还是编辑实验室的标识
const isAddLabForm = ref(null);

// 显示右键菜单标识
const isContentMenuOpen = ref(false);

// 右键挂载元素
const eventVal = ref({});

// 右键菜单列表
const menus = ref({
  menus: [
    // {
    //   label: "修改实验室名称",
    //   click: () => {
    //     console.log("修改实验室名称", currentContextmenuData.value);
    //   }
    // },
    {
      label: "添加实验室",
      icons: "plus",
      click: () => {
        console.log("添加子实验室", currentContextmenuData.value);
        if (currentContextmenuData.value.tags != 4) {
          isAddLabForm.value = true;
          clearAddEditFormF();
          isShowAddLaboratoryDialog.value = true;
        } else {
          ElMessage.error("此级不允许添加实验室!");
        }
      }
    },
    {
      label: "编辑实验室",
      icons: "edit",
      click: () => {
        console.log("编辑实验室", currentContextmenuData.value);
        isAddLabForm.value = false;
        addLaboratoryFormData.value.id = currentContextmenuData.value.id;
        addLaboratoryFormData.value.address = currentContextmenuData.value.address;
        // addLaboratoryFormData.value.name = currentContextmenuData.value.label
        isShowAddLaboratoryDialog.value = true;
        // if (currentContextmenuData.value. tags != 3) {

        // } else {
        //   ElMessage.error("此级不允许添加实验室!");
        // }
      }
    },
    {
      label: "删除实验室",
      icons: "delete",
      click: () => {
        console.log("删除实验室", currentContextmenuData.value);
        delLabClick();
      }
    }
  ]
});

// 清除添加/编辑 表单的函数
const clearAddEditFormF = () => {
  addLaboratoryFormData.value = {
    id: null,
    address: ""
  };
};

// 修改实验室点击回调
// const editLabClickCallBack = () => {
//   console.log("修改实验室名称", currentContextmenuData.value);
// };

// // 添加子实验室名称点击回调
// const addChildrenLabClickCallBack = () => {
//   console.log("添加子实验室", currentContextmenuData.value);
// };

// // 删除实验室点击回调
// const delLabClickCallBack = () => {
//   console.log("删除实验室", currentContextmenuData.value);
// };

// 加载标识
const isLoading = ref(false);

// 显示添加实验室弹窗标识
const isShowAddLaboratoryDialog = ref(false);

// 添加实验室表单数据
const addLaboratoryFormData = ref<addLaboratoryFormType>({
  id: null,
  address: ""
});

// 添加实验室表单Ref
const addLaboratoryFormRef = ref(null);

// 添加实验室表单校验规则
const addLaboratoryFormRules = ref({
  address: [{ required: true, message: "请输入实验室地址", trigger: "blur" }]
});

interface Tree {
  id: number;
  label: string;
  children?: Tree[];
}

const filterText = ref(0);
const treeRef = ref<any>(null);

// 树形节点过滤函数
// const filterNode = (value: string, data: Tree) => {
//   if (!value) return true;
//   console.log(data);
//   console.log(value);

//   return data.disabled == filterText.value;
// };
// let id = 1000;

// 当前点击的节点id
const currentClickNodeId = ref<null | number>(null);

// 添加实验室点击事件
// const addLaboratoryClick = data => {
//   // console.log(data);

//   // currentClickNodeId.value = id;
//   isShowAddLaboratoryDialog.value = true;
// };

// 添加实验室确定点击事件
const addLaboratoryConfirmClick = async formRef => {
  if (!formRef) return;
  await formRef.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      if (isAddLabForm.value) {
        addLaboratoryFunc();
      } else {
        editLaboratoryFunc();
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 添加实验室请求函数
const addLaboratoryFunc = async () => {
  await addLaboratoryApi({
    name: addLaboratoryFormData.value.name,
    address: addLaboratoryFormData.value.address,
    pid: currentClickNodeId.value
  })
    .then(res => {
      console.log("添加成功", res);
      ElMessage.success("添加成功");
    })
    .catch(err => {
      console.log("添加失败", err);
      ElMessage.error("添加失败");
    })
    .finally(() => {
      isShowAddLaboratoryDialog.value = false;
      // 重新加载数据
      selectLaboratoryFunc();
    });
};

// 编辑实验室请求函数
const editLaboratoryFunc = async () => {
  console.log("编辑实验室");
  await editLaboratoryApi({
    name: addLaboratoryFormData.value.name,
    address: addLaboratoryFormData.value.address,
    id: addLaboratoryFormData.value.id
  })
    .then(res => {
      console.log("编辑成功", res);
      ElMessage.success("编辑成功");
    })
    .catch(err => {
      console.log("编辑失败", err);
      ElMessage.error("编辑失败");
    })
    .finally(() => {
      isShowAddLaboratoryDialog.value = false;
      // 重新加载数据
      selectLaboratoryFunc();
    });
};

// 删除实验室点击事件
const delLabClick = () => {
  ElMessageBox.confirm("确认要删除这个实验室吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      delLaboratoryFunc();
    })
    .catch(() => {});
};

// 删除实验室的请求函数
const delLaboratoryFunc = async () => {
  console.log("当前删除的id", currentClickNodeId.value);
  await delLaboratoryApi({
    tbLabId: currentClickNodeId.value
  })
    .then(res => {
      if (res.status == 400) {
        ElMessage.error(res.msg);
      } else {
        ElMessage.success("删除成功");
      }
    })
    .catch(err => {
      ElMessage.error("删除失败");
    })
    .finally(() => {
      selectLaboratoryFunc();
    });
};

// 编辑实验室点击事件
// const editLaboratorClick = e => {
//   console.log(e);
// };

// 删除实验室点击事件
// const delLaboratorClick = e => {
//   console.log(e);
// };

// 树节点点击事件
const treeNodeClick = e => {
  console.log("点击节点", e);
  currentClickNodeId.value = e.id;
  console.log("当前点击id", currentClickNodeId.value);
};

// 树节点双击
// const nodeDblClick = (e, a) => {
//   console.log(e, a);
//   isContentMenuOpen.value = true;
// };

const renderContent = (
  h,
  {
    node,
    data,
    store
  }: {
    node: Node;
    data: Tree;
    store: Node["store"];
  }
) => {
  return h(
    "span",
    {
      class: "custom-tree-node"
    },
    // h(
    //   'span',
    //   node.tags
    // ),
    h(data.children?.length != 0 ? LabImg1 : LabImg),
    // h(LabImg),
    h(
      "span",
      {
        class: "cccsdaasdsadsa"
      },
      node.label
    ),
    h("div")
  );
};

const dataSource = ref<laboratoryListType>();

// 处理实验室结构数据的函数
const disposeLaboratoryDataFunc = (data: laboratoryListType) => {
  console.log("dis", data);
  let nData = [];
  // 处理数据
  data.children = data.tbTabRspList;
  data.label = data.address;
  data.disabled = data.status;
  delete data.tbTabRspList;

  // 判断是否存在子数据，进行递归遍历
  if (data.children && data.children.length != 0) {
    data.children.forEach((item: laboratoryListType) => {
      disposeLaboratoryDataFunc(item);
    });
  }
};

// 添加层级标识的函数
const addTierTagFunc = () => {
  if (dataSource.value)
    // 遍历第一层
    dataSource.value?.forEach(item1 => {
      item1.tags = 1;
      if (item1.children && item1.children?.length != 0) {
        // 遍历第二层
        item1.children.forEach(item2 => {
          item2.tags = 2;
          if (item2.children && item2.children?.length != 0) {
            // 遍历第三层
            item2.children.forEach(item3 => {
              item3.tags = 3;
              if (item3.children && item3.children?.length != 0) {
                // 遍历第四层
                item3.children.forEach(item4 => {
                  item4.tags = 4;
                });
              }
            });
          }
        });
      }
    });
  console.log("添加层级", dataSource.value);
};

// 查询实验室结构的函数
const selectLaboratoryFunc = async () => {
  isLoading.value = true;
  await selectLaboratoryApi().then(res => {
    console.log("实验室列表", res.data);
    res.data.forEach((item: laboratoryListType) => {
      console.log(item);
      disposeLaboratoryDataFunc(item);
    });
    console.log("rh", res.data);
    dataSource.value = res.data;
    addTierTagFunc();
    isLoading.value = false;
    filterText.value = 0;
    setTimeout(() => {
      filterText.value = 1;
    }, 10);
  });
};

onMounted(() => {
  selectLaboratoryFunc();
});
</script>

<style lang="scss" scoped>
.laboratory_wrap {
  width: 100%;
  height: 100%;
  .laboratory_wrap_card {
    width: 100%;
    height: 100%;
    .title_box {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      width: 480px;
      padding: 0 10px 10px 0;
      .title_text {
        font-size: 18px;
        font-weight: bold;
        letter-spacing: 1px;
        .iconfont {
          position: relative;
          top: 1px;
          font-size: 22px;
          color: #2a8ff4;
        }
      }
    }
  }
  .add_laboratory_box {
    width: 450px;
    padding: 30px 40px 20px 30px;
  }
}
:deep(.custom-tree-node) {
  display: flex;
  flex: 1;
  align-items: center;
  padding-top: 4px;

  /* // justify-content: space-between !important; */
  padding-right: 8px;
  padding-bottom: 4px;
  font-size: 14px;

  /* // background-color: #0817ec; */
}
.custom-tree-container {
  width: 100%;
  height: 86%;
}
:deep(.laboratory_wrap_card .el-card__body) {
  height: 100%;
}
.lab_tree {
  max-width: 480px;
  height: 700px;
  padding: 14px;
  margin-top: 10px;
  overflow-y: auto;
  border: 2px dashed #cccccc;
}

/* // :deep(.is-checked) {
//   background: red;
// }
// :deep() {
//   padding: 0 !important;
// } */
:deep(.el-tree-node) {
  /* // padding: 4px 0; */
  .el-tree-node__content {
    box-sizing: content-box;
    padding-top: 2px !important;
    padding-bottom: 2px !important;
  }
}
</style>

<!-- // 遍历第一层
  data.forEach(item1 => {
    // 处理第一层
    item1.children = item1.tabRspList;
    delete item1.tabRspList;
    item1.label = item1.address;
    console.log("item1", item1);
    if (item1.children && item1.children.length != 0) {
      // 遍历第二层
      item1.children.forEach(item2 => {
        // 处理第二层
        item2.children = item2.tabRspList;
        delete item2.tabRspList;
        item2.label = item2.address;
        console.log("item2", item2);
        if (item2.children && item2.children.length != 0) {
          // 遍历第三层
          item2.children.forEach(item3 => {
            // 处理第三层
            item3.children = item3.tabRspList;
            delete item3.tabRspList;
            item3.label = item3.address;
            console.log("item3", item3);
            if (item3.children && item3.children.length != 0) {
              // 遍历第四层
              item3.children.forEach(item4 => {
                // 处理第四层
                item4.children = item4.tabRspList;
                delete item4.tabRspList;
                item4.label = item4.address;
                console.log("item4", item4);
              });
            }
          });
        }
      });
    }

    // console.log(item);
  }); -->
